define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var util = require('util');
	var utilDSP = require('modules/common');
	var TERMINAL_TYPE = pubjs.config("CONST/TERMINAL_TYPE") || [];
	var List = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-campaignList'
				,urlRemove: 'plan/remove'
				,urlRecover:'plan/recover'
				,navEdit: 'admin/customDownload/edit'
				,navSaveAs: 'admin/customDownload/saveAs'
				,urlReset: 'customDownload/reset'
				,addHref: 'plan/edit'	// 新建路径
				,editHref: 'plan/edit/'	// 编辑路径
				,addHrefBrand: 'serving/planEdit'	// 品牌版新建路径
				,editHrefBrand: 'serving/planEdit/'	// 品牌版编辑路径
				,'vModel': {
					'view': {
						'addButton': true
					},
					'vmClickAdd': this.eventClickAdd
				}
				,param:{
					AdvertiserId: +util.getQueryString('aderId'),
				}
			});

			this.Super('init', arguments);
		}
		,afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			this.append($([
				'<div class="M-formHead">',
					'<button v-show="view.addButton" class="btn btn-primary" v-on:click="vmClickAdd">'+LANG('新建计划')+'</button>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="" pub-name="grid" pub-mod="plan/grid/list.base"/>'
			].join('')));

			self.vm.mount();

			this.buildFromTemplate({
				grid: {
					'hasFilter': true,
					'hasMenu': pubjs.checkRight('plan.update'),
					'hasBatch': pubjs.checkRight('plan.update'),
					'param': c.param
				}
			});
			self.createAsync('slotSidebar', '@layout/v1/sidebar.base', {
				'target': c.targetSidebar,
				'items': [
					{'name': 'client', 'uri':'modules/sideBarBase.radio', 'config': {
						'title': LANG('终端：'),
						'data': TERMINAL_TYPE,
						value:0
					}},
					{'name': 'qualification', 'uri': 'modules/sideBarBase.qualificationRadio', 'config': {
						'title': LANG('广告主：'),
						'data': [
							{id: 0, name: LANG('全部')},
							{id: 1, name: LANG('指定广告主')}
						],
						'value': 0,
						'select_config': {
							url: 'qualification/list',
							name: LANG('添加筛选广告主'),
							grid_mod: 'campaign/modules/select.grid',
							param: {
								// 'no_limit': true
							},
							gridTitle: LANG('选择广告主')
						}
					}},
					{'name': 'status', 'uri':'modules/sideBarBase.radio', 'config': {
						'title': LANG('状态：'),
						'data': [
							{id: 0, name: LANG('所有有效活动')},
							{id: 2, name: LANG('进行中')},
							{id: 4, name: LANG('已暂停')},
							{id: 3, name: LANG('已结束')},
							{id: 1, name: LANG('未开始')},
							{id: 5, name: LANG('超预算')},
							{id: 6, name: LANG('草稿')},
							{id: 7, name: LANG('已归档')}
						],
						'value': 0
					}},
					{'name': 'label', 'uri':'modules/sideBarBase.label', 'config': {
						url: 'plan/labels'
					}},
					{'name': 'metrics', 'uri':'modules/sideBarBase.metrics', 'config': {
						'metrics': ["{front}","{back}","{conversion}","{cost}"]
					}}
				]
			});

			self.createAsync('batchEdit', 'campaign/popwin/batchEdit.main', {
				types: {
					date:
					{
						url: 'plan/setPeriod'
					},
					limit:
					{
						module: 'plan/modules/limit.batchEdit',
						url: 'plan/setLimit'
					},
					zone:
					{
						url: 'plan/setZone'
					},
					nameReplace:
					{
						url: 'plan/nameReplace'
					}

				}
			});
		}
		,eventClickAdd: function(ev){
			var c = this.getConfig();
			pubjs.controller.navigate(c.isBrand ? c.addHrefBrand + utilDSP.getBrandSearch() : c.addHref);
		}
		,onSidebarFilter: function(ev){
			var self = this
				,param = {};
			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;

				switch (type) {
					case 'client':
						param.Clients = +id;
						break;
					case 'status':
						param.Status = +id;
						break;
					case 'label':
						param.Labels = id;
						break;
					case 'qualification':
						param.qualificationIds = item.data;
						break;
					case 'metrics':
						param.metrics_filter = id;
				}
			});

			self.$.grid.setParam(param).load();
		}
		,onSidebarFilterGroup: function(ev)
		{
			if (ev.name == 'qualification')
			{
				if(ev.param.data.length){
					this.$.grid.reload({'qualificationIds': ev.param.data});
				}
				this.cast('sidebarFilterResult', {'qualification': ev.param});
			}
		}
		,onMainPopwinOk: function(){
			this.$.grid.showPanel();
			return false;
		}
		,onInputClick: function(ev) {
			return false;
		}
		,reload: function() {
			this.$.grid.reload({AdvertiserId: +util.getQueryString('aderId')});
		}
		,reset: function() {

		}
		,send: function(url, param, cbName) {
			if (url) {
				pubjs.loading.show();
				var self = this;
				pubjs.mc.send(url, param, function (err) {
					pubjs.loading.hide();
					if (err) {
						return pubjs.alert(err.message);
					}
					self[cbName || 'reload'].apply(self, arguments);
				});
			}
		}
		// 操作菜单-下拉菜单界面
		,onOperateMenuShow: function(ev){
			/**
			 Status：
			 1 正常/进行中
			 2 暂停
			 3 草稿
			 4 未开始
			 5 已结束
			 6 超预算
			 7 归档
			 **/

			var param = ev.param;
			var result = [];
			// 默认计划，不可编辑
			if (param._id == 0)
			{
				return false;
			}

			if(!param.IsDeleted)
			{
				if(param.Status != 3)
				{
					if (param.Status === 1 && pubjs.checkRight('plan.pause'))
					{
						result.push({id: 'pause', name: LANG('暂停')});
					}
					else if (pubjs.checkRight('plan.start'))
					{
						result.push({id: 'start', name: LANG('开启')});
					}
					//检查是否有编辑权限
					if (pubjs.checkRight('plan.update'))
					{
						result.push({id: 'edit', name: LANG('编辑')});
					}
					//检查是否有删除权限
					if (pubjs.checkRight('plan.remove'))
					{
						result.push({id: 'delete', name: LANG('归档')});
					}
				}
				else
				{
					if (pubjs.checkRight('plan.update'))
					{
						result.push({id: 'edit', name: LANG('编辑')});
					}
				}
			}
			else
			{
				if (pubjs.checkRight('plan.recover'))
				{
					// 已归档的只有'还原'操作
					result.push( {id: 'recover', name: LANG('还原')} );
				}
			}
			//检查是否有另存为权限,存在未解决的情况是广告主已经归并了无法使用另存为，必须允许先还原再另存为
			if (pubjs.checkRight('plan.add'))
			{
				result.push({id: 'saveas', name: LANG('另存为')});
			}
			ev.returnValue = result;
			return false;
		}
		// 操作菜单-响应菜单操作
		,onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			var id = +data._id;
			var self = this;
			var c = self.getConfig();

			switch(op.key){
				case 'start':
					self.send('plan/start', {'id': id }, 'afterOperate');
					break;
				case 'pause':
					self.send('plan/pause', {'id': id }, 'afterOperate');
					break;
				case 'delete':
					pubjs.confirm(LANG('确认归档计划 %1 吗', id), function(state) {
						if(state)
						{
							pubjs.mc.send(self.getConfig('urlRemove'),{'_id': id},
								self.onRemove.bind(self)
							);
						}
					});
					break;
				case 'recover':
					pubjs.mc.send(self.getConfig('urlRecover'), {'_id': id },self.onRecover.bind(self));
					break;
				case 'edit':
					pubjs.controller.navigate(c.editHrefBrand + id + utilDSP.getBrandSearch());
					break;
				case 'saveas':
					window.open('#plan/saveas/' + id);
			}

			return false;
		}
		,onBatchShow: function(ev){
			var list = [];
			if (pubjs.checkRight('plan.update'))
			{
				list = [
					{
						id: 'set',
						name: LANG('设置'),
						subs: [
							{id: 'batchEdit.limit', name: LANG("修改预算")},
							{id: 'batchEdit.date', name: LANG("投放日期")},
							{id: 'batchEdit.zone', name: LANG("投放地区")},
							{id: 'batchEdit.nameReplace', name: LANG('计划名称关键词替换')}
						]
					}
				];
			}

			var batch = [
				{id: 'pause', name: LANG('暂停'), right: 'plan.pause'},
				{id: 'start', name: LANG('开始'), right: 'plan.start'},
				{id: 'export', name: LANG('导出'), right: 'plan.list'}
			];

			// 检查权限
			util.each(batch, function(item){
				if(!item.right || pubjs.checkRight(item.right))
				{
					list.push(item);
				}
			});

			ev.returnValue = list;
			return false;
		}
		// 批量操作-响应菜单操作
		,onBatchSelect: function(ev){
			var data = ev.param[0];
			var ids = ev.param[1];
			var contents = ev.param[2];
			var key = data.key || '';

			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择计划'));
				return false;
			}

			// 设置子菜单的部分内容编辑,id是用点分割
			var keys = key.split('.');
			if (keys.shift() === 'batchEdit') {
				this.$.batchEdit.reset().show().setTitle(data.name).setType(keys.shift()).setParam(ids);
				return false;
			}

			var self = this;
			switch(key){
				case 'start':
					self.send('plan/start',{'id': ids }, 'onBatchEditSuccess');
					break;
				case 'pause':
					self.send('plan/pause',{'id': ids }, 'onBatchEditSuccess');
					break;
				/*case 'delete':
					pubjs.confirm(LANG('确认删除以下活动 %1 吗', ids), function(state) {
						if(state)y
						{
							self.send('campaign/remove',{'id': ids }, 'onBatchEditSuccess');
						}
					});
					break;
				case 'recover':
					self.send('campaign/recover',{'id': ids }, 'onBatchEditSuccess');
					break;*/
				case 'export':
					var url = utilDSP.getExportApi(this.get('grid'), ids);
					window.location.href = url;
					break;
			}

			return false;
		}
		,onBatchEditSuccess: function(err, data)
		{
			if(data)
			{
				if(!data.ids || !data.ids.length)
				{
					return pubjs.alert(LANG('操作失败'));
				}
			}

			var ids = this.$.grid.getSelectRowIds();
			// 本页grid
			pubjs.core.cast('savePlanSuccess', {ids: ids});
			// 其他tab的grid
			if (utilDSP.checkOpener() && window.opener && window.opener.pubjs)
			{
				window.opener.pubjs.core.cast('savePlanSuccess', {ids: ids});
			}

			this.$.grid.setSelectRowIds([]);
			this.reload();
			return false;
		}
		,afterOperate: function(err, data)
		{
			if(!data || !data.ids || !data.ids.length)
			{
				return pubjs.alert(LANG('操作失败'));
			}

			pubjs.notify(LANG('操作成功'));
			this.reload();
			return false;
		}
		,onSavePlanSuccess: function(ev)
		{
			this.reload();

			if (ev.param && ev.param.id)
			{
				this.$.grid.setRowHighlight(ev.param.id);
			}

			if (ev.param && ev.param.ids && ev.param.ids.length)
			{
				var ids = ev.param.ids;
				for (var i = 0; i < ids.length; i++)
				{
					this.$.grid.setRowHighlight(+ids[i]);
				}
			}
		}
		,onRemove: function( err, data ) {
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert('归档成功');
			this.reload();
		},
		onRecover: function( err, data ) {
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert('还原成功');
			this.reload();
		},
	});

	exports.base = List;
});